package com.touchfired.common.core.listener.impl;

import com.alibaba.fastjson.JSON;
import com.touchfired.common.constants.ClientInfo;
import com.touchfired.common.constants.GlobalConstants;
import com.touchfired.common.context.ServerContext;
import com.touchfired.common.core.callback.Callback;
import com.touchfired.common.core.event.impl.ConnectedEvent;
import com.touchfired.common.core.listener.BaseListener;
import com.touchfired.common.message.impl.SocketMessage;
import com.touchfired.common.message.transfer.MessageConsoler;
import com.touchfired.common.message.transfer.MessageSender;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.HttpHeaders;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 客户端连接监听器
 *
 * @author 幸佳俊
 */
@Order(0)
@Component
public class ConnectedListener extends BaseListener<ConnectedEvent> {

    private final ServerContext serverContext;

    public ConnectedListener(ServerContext serverContext) {
        this.serverContext = serverContext;
    }

    @Override
    public void onEvent(ConnectedEvent connectedEvent, Callback callback) {
        ClientInfo clientInfo = new ClientInfo();
        Channel channel = connectedEvent.getCtx().channel();
        String remoteAddress = channel.remoteAddress().toString().substring(1);

        // 获取客户端
        String username = "";
        HttpHeaders headers = connectedEvent.getHeaders();
        if (headers.contains(GlobalConstants.CLIENT_NAME)) {
            username = headers.get(GlobalConstants.CLIENT_NAME);
        }
        if (StringUtils.isBlank(username)) {
            username = remoteAddress.split(":")[0];
        }

        // 保存客户端信息
        String longId = channel.id().asLongText();
        clientInfo.setLongId(longId)
                .setName(username)
                .setChannel(channel)
                .setHost(remoteAddress);
        serverContext.addClientInfo(clientInfo);
        MessageConsoler.info(remoteAddress + "连接成功");
        MessageSender.send(channel, new SocketMessage(JSON.toJSONString(clientInfo)));
    }

}
